package com.xxkj.orcfx.utils;

/**
 * <br>TODO(描述该类的作用)</br>
 *
 * @author 516649
 * @email zhouqian@dafycredit.com
 * @date 2017年9月2日 下午2:46:05
 * @version 1.0
 * @since 1.0
 */

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * <br>TODO(描述该类的作用)</br>
 *
 * @author 516649
 * @version 1.0
 * @email zhouqian@dafycredit.com
 * @date 2017年9月2日 下午3:42:12
 * @since 1.0
 */

@SuppressWarnings("deprecation")
public class HttpsClientUtil {

    static final int timeOut = 20 * 1000;

    private static CloseableHttpClient httpClient = null;

    private final static Object syncLock = new Object();

    private static void config(HttpRequestBase httpRequestBase) {
        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut)
                .setSocketTimeout(timeOut).build();
        httpRequestBase.setConfig(requestConfig);
    }

    /**
     * 获取HttpClient对象
     *
     * @return
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static CloseableHttpClient getHttpClient(String url) {
        String hostname = url.split("/")[2];
        int port = 80;
        if (hostname.contains(":")) {
            String[] arr = hostname.split(":");
            hostname = arr[0];
            port = Integer.parseInt(arr[1]);
        }
        if (httpClient == null) {
            synchronized (syncLock) {
                if (httpClient == null) {
                    httpClient = createHttpClient(200, 40, 100, hostname, port);
                }
            }
        }
        return httpClient;
    }

    /**
     * 创建HttpClient对象
     *
     * @return
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname, int port) {

        // 采用绕过验证的方式处理https请求

        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = createSSLConnSocketFactory();

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf).register(
                "https", sslsf).build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
        // 将最大连接数增加
        connManager.setMaxTotal(maxTotal);
        // 将每个路由基础的连接增加
        connManager.setDefaultMaxPerRoute(maxPerRoute);
        HttpHost httpHost = new HttpHost(hostname, port);
        // 将目标主机的最大连接数增加
        connManager.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
        // 请求重试处理
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {

            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 5) {// 如果已经重试了5次，就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接，那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return false;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// SSL握手异常
                    return false;
                }

                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的，就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).setRetryHandler(httpRequestRetryHandler)
                .build();
        return httpClient;
    }

    private static void setPostParams(HttpPost httpost, Map<String, String> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            if (params.get(key) != null) nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static void setPostParamsObject(HttpPost httpost, Map<String, Object> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            if (params.get(key) != null) nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static void setPostParamsObject(HttpPost httpost, String paramsJson) {
        try {
            httpost.addHeader("Content-Type", "application/json");
            httpost.addHeader("Accept", "application/json");
            StringEntity se = new StringEntity(paramsJson, ContentType.APPLICATION_JSON);
            httpost.setEntity(se);
        } catch (UnsupportedCharsetException e) {
            e.printStackTrace();
        }
    }

    private static HttpGet getHttpGet(String url, Map<String, String> params) throws URISyntaxException {
        if (params == null || params.size() == 0) {
            return new HttpGet(url);
        }
        URIBuilder uriBuilder = new URIBuilder(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            if (params.get(key) != null) nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        uriBuilder.setParameters(nvps);
        return new HttpGet(uriBuilder.build());
    }

    /**
     * GET请求URL获取内容
     *
     * @param url
     * @return
     * @throws IOException
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static String post(String url, Map<String, Object> params) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        setPostParamsObject(httppost, params);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httppost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String post(String url, String paramsJson) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        setPostParamsObject(httppost, paramsJson);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httppost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String postForm(String url, Map<String, String> paramMap,Header[] headers) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        httppost.setHeaders(headers);
        // 创建参数队列
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532).setMode(HttpMultipartMode.RFC6532);
        builder.setCharset(Charset.forName(HTTP.UTF_8));
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (String paramKey : paramMap.keySet()) {
            if (paramMap.get(paramKey) == null) continue;
            builder.addPart(paramKey, new StringBody(paramMap.get(paramKey), contentType));
        }

        httppost.setEntity(builder.build());
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = getHttpClient(url).execute(httppost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
        return result;
    }


    public static String postForm(String url, Map<String, String> paramMap) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        // 创建参数队列
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532).setMode(HttpMultipartMode.RFC6532);
        ;
        builder.setCharset(Charset.forName(HTTP.UTF_8));
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (String paramKey : paramMap.keySet()) {
            if (paramMap.get(paramKey) == null) continue;
            builder.addPart(paramKey, new StringBody(paramMap.get(paramKey), contentType));
        }

        httppost.setEntity(builder.build());
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = getHttpClient(url).execute(httppost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
        return result;
    }

    public static byte[] postByte(String url, String paramsJson) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        setPostParamsObject(httppost, paramsJson);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httppost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            byte[] result = EntityUtils.toByteArray(entity);
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] postByte(String url, Map<String, Object> params) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        setPostParamsObject(httppost, params);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httppost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            byte[] result = EntityUtils.toByteArray(entity);
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * GET请求URL获取内容
     *
     * @param url
     * @return
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static String get(String url) {
        HttpGet httpget = new HttpGet(url);
        config(httpget);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httpget, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static byte[] getByte(String url) {
        HttpGet httpget = new HttpGet(url);
        config(httpget);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httpget, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            byte[] result = EntityUtils.toByteArray(entity);
            EntityUtils.consume(entity);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String get(String url, Map<String, String> pramMap) throws Exception {
        HttpGet httpget = getHttpGet(url, pramMap);
        config(httpget);
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient(url).execute(httpget, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String postFile(String url, Map<String, String> paramMap, Map<String, File> fileParam) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        // 创建参数队列
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532).setMode(HttpMultipartMode.RFC6532);
        ;
        builder.setCharset(Charset.forName(HTTP.UTF_8));
        for (String fileKey : fileParam.keySet()) {
            File f = fileParam.get(fileKey);
            builder.addBinaryBody(fileKey, new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName());
        }
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (String paramKey : paramMap.keySet()) {
            if (StringUtils.isEmpty(paramMap.get(paramKey))) continue;
            builder.addPart(paramKey, new StringBody(paramMap.get(paramKey), contentType));
        }

        httppost.setEntity(builder.build());
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = getHttpClient(url).execute(httppost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
        return result;
    }


    public static String postByte(String url, Map<String, String> paramMap, Map<String, byte[]> fileParam) throws IOException {
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        // 创建参数队列
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        builder.setCharset(Charset.forName(HTTP.UTF_8));
        for (String fileKey : fileParam.keySet()) {
            builder.addBinaryBody(fileKey, fileParam.get(fileKey));
        }
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (String paramKey : paramMap.keySet()) {
            if (StringUtils.isEmpty(paramMap.get(paramKey))) continue;
            builder.addPart(paramKey, new StringBody(paramMap.get(paramKey), contentType));
        }
        HttpEntity b = builder.build();
        httppost.setEntity(builder.build());
        CloseableHttpResponse response = getHttpClient(url).execute(httppost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
        return result;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    @SuppressWarnings("deprecation")
    public static SSLConnectionSocketFactory createSSLConnSocketFactory() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }
            });
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return sslsf;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        /*String url = "https://180.163.3.84:8090/fcgi-bin/zx_upload_data.fcgi?req={\"random\":\"rguMtM\",\"data\":[{\"identifier\":\"2F0C60FA7BCE6565FBC063A4AED256F87ADC61EBF5391B89D192DBE5B8F6B1C1\",\"status_start_time\":\"2017-08-30 18:18:23\",\"business\":\"1\",\"status_amount\":\"6500\",\"product_id\":\"10003\",\"status_des\":\"当期全额还清\",\"memo\":\"\",\"trans_start_time\":\"2017-08-25 10:25:23\",\"business_seq\":\"550E840045115278992\",\"status\":\"108\"}],\"ent_no\":\"40002019\",\"type\":1,\"rows\":1,\"report_date\":\"2017-08-31\"}";
        String josnStr = "{\"random\":\"rguMtM\",\"data\":[{\"identifier\":\"2F0C60FA7BCE6565FBC063A4AED256F87ADC61EBF5391B89D192DBE5B8F6B1C1\",\"status_start_time\":\"2017-08-30 18:18:23\",\"business\":\"1\",\"status_amount\":\"6500\",\"product_id\":\"10003\",\"status_des\":\"当期全额还清\",\"memo\":\"\",\"trans_start_time\":\"2017-08-25 10:25:23\",\"business_seq\":\"550E840045115278992\",\"status\":\"108\"}],\"ent_no\":\"40002019\",\"type\":1,\"rows\":1,\"report_date\":\"2017-08-31\"}";
        String urltest = String.format("%s?req=%s", "https://180.163.3.84:8090/fcgi-bin/zx_upload_data.fcgi", URLEncoder.encode(josnStr,
                        "utf-8"));
        String response = get(urltest);*/

        String resp = get(String.format("https://qq.ip138.com/idsearch/index.asp?userid=%s&action=idcard", "222421197002240816"));

        System.out.println(resp);
    }

}
